import React, { useContext, useState, useImperativeHandle, useEffect, useMemo } from 'react';
import { Button, Table, Empty, Spin, Tooltip, message, Form, Checkbox, Switch } from 'antd';
import { history } from 'umi';
import lodash from 'lodash';
import UpdateMaterialModal from './UpdateMaterialModal';
import UpdateRemoveModal from './UpdateRemoveModal';
import { getPackTableColumns } from '../mconfig';
import { ApplyUpdateContext } from '../common/ApplyContext';
import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';
import { useStepPack } from '../common/useStepPack';
import { useStepTarget } from '../common/useStepTarget';
import { PlusOutlined, DeleteOutlined, EyeOutlined, SearchOutlined, EyeInvisibleOutlined } from '@ant-design/icons';
import CustomPaging from '@/components/CustomPaging';
import { DescriptionsType, useDescriptionsType } from '@/components/DescriptionsType';
import { getColorTextLoadMap, getKeyRouter, getLoadMapList, getTenantID } from '@/utils';
import pageStyles from '@/common/pageLayout.less';
import { IContractsActionEnum } from '../common/ApplyReducer';
import { ILoadMapTypeAll } from '@/common';
import { UploadFormCommon } from '@/components/UploadForm';
import {
  GoveCentralPurchse,
  LaboratorySelfOrg,
  QC_SQSTATE,
  handleReturnObjectData,
  processObjects,
  setTableRowClassName,
  supplyWayList,
  combineObjects,
  SHZ_SQSTATE,
  ZF_SQSTATE,
} from '../common/Format';
import MyIcon from '@/components/MyIcon';
import _ from 'lodash';
import Cls from 'classnames';
import '../common/style.less';
import { renderFileFunc } from '../../Acommon';
import AfewMetailModalCpt from '../common/AddMetailModal/UpdateNeedMaterialModal';
import UpdateProjectModal from './UpdateProjectModal';
import { IntentModal } from './IntentModal';
import SelectProjectModal from '../../Acomponents/SelectProjectModal/SelectProjectModal';
// import { SelectProjectModal } from './SelectProjectModal';

const UpdateStepsPack = React.forwardRef(({ onClickSave }: Record<string, any>, ref) => {
  /** 采购方式字典 */
  const loadMdicIds: string[] = [`${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}`];
  const { loadMapInfo: dictionaryData, mapLoading } = getLoadMapList(loadMdicIds);
  const purchaseFs = dictionaryData?.[`${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}`];

  /** 上下文 */
  const {
    isShowSubmit,
    curRes,
    prefixCls,
    applyInfo,
    dispatch,
    ProjectInfo,
    successMaterials,
    setSuccessMaterials,
    finallyType,
    packData,
    setPackData,
    reloadInfoService,
  } = useContext(ApplyUpdateContext);

  /** 当前标包页数 */
  const [page, setPage] = useState<number>(0);
  /** loading */
  const [loading, setLoading] = useState<boolean>(false);
  /** 可不使用变量，但需要改方法体 */
  const [treeSearch, setTreeSearch] = useState<string>('');
  /** 保存一份表单选择[采购组织类型] */
  const [purchaseType, setPurchaseType] = useState<string>(LaboratorySelfOrg());
  /** 打开零星采购物料弹窗 */
  const [afewMetailModal, setAfewMetailModal] = useState<Record<string, any>>({});
  /** 是否显示意向公开弹窗 */
  const [isShowIntentModal, setIsShowIntentModal] = useState<Record<string, any>>({});
  /** 是否显示项目来源弹窗 */
  const [isShowProjectModal, setIsShowProjectModal] = useState<Record<string, any>>({});

  /**资金来源弹窗组件渲染状态*/
  const [isShowSelectProject, setIsShowSelectProject] = useState<boolean>(false);
  const onChangeSelectProjectState = (state: boolean, param: Record<string, any> = {}) => {
    setIsShowSelectProject(state);
    if (Object.keys(param).length) {
      /** 给表单赋值 */
      // setFieldsValue({ projectName: param.projectName, projectCode: param.projectCode });
      /** 给reducer */
      dispatch({ type: IContractsActionEnum.UpdataProJect, payload: param });
    }
  };

  /** 处理树数据 */
  const orgTreeData = (data: any[]): any[] => {
    return data?.map((item: any) => {
      const name = item?.name;
      const nameLength = name?.length;
      const select = name?.search(treeSearch);
      const searchLength = treeSearch?.length;
      const afterStr = name?.slice(0, select);
      const selectStr = treeSearch;
      const beforeStr = name?.slice(select + searchLength, nameLength);
      const titleTree =
        select > -1 && selectStr ? (
          <span className={pageStyles['over-flow-hidden']}>
            {afterStr}
            <span style={{ color: '#f50' }}>{selectStr}</span>
            {beforeStr}
          </span>
        ) : (
          <span className={pageStyles['over-flow-hidden']}>{item?.name}</span>
        );

      if (item?.children && item?.children?.length > 0) {
        return {
          ...item,
          title: <div id={item?.id}>{titleTree}</div>,
          searchTitle: item?.name,
          key: item?.id,
          value: item?.id,
          children: orgTreeData(item?.children),
        };
      }
      return {
        ...item,
        title: <div id={item?.id}>{titleTree}</div>,
        searchTitle: item?.name,
        key: item?.id,
        value: item?.id,
      };
    });
  };

  /** 展示不同的下拉选择拟采数据 */
  const procureRealListMemo = useMemo(() => {
    if (!purchaseType) return [];
    if (purchaseType && purchaseFs?.length) {
      const result = purchaseFs?.find((item) => item?.id == purchaseType);
      if (result?.children && result?.children?.length) {
        return result?.children;
      } else {
        return [];
      }
    }
    return [];
  }, [purchaseType, purchaseFs]);

  const [formRef] = Form.useForm(); /**表单实例*/

  /** 表格表单配置 */
  const [config, methods] = useDescriptionsType({
    labelWidth: 240,
    basicForm: formRef,
    isShowNumTitle: true,
    schemas: [
      {
        key: 'applyInfoDes',
        title: '基本信息',
        isNoShowNum: true,
        fieldChildren: [
          {
            label: '标包名称',
            field: 'packName',
            component: 'Input',
            required: true,
            placeholder: '请输入',
            disabled: !isShowSubmit,
            onChange: (ev) => {
              let val = ev?.target?.value;
              let newPackData = _?.cloneDeep(packData);
              newPackData[page - 1].packName = val;
              setPackData(newPackData);
            },
          },
          {
            label: '包号',
            field: 'packCode',
            component: 'Input',
            placeholder: '自动带出',
            disabled: true,
          },
          // {
          //   label: '标的类别',
          //   field: 'supplyTypeName',
          //   component: 'Render',
          //   slotRender: (text: string) => {
          //     const { colorText, color } = getColorTextLoadMap(text);
          //     if (colorText) {
          //       return <div style={{ color, paddingLeft: '8px' }}>{colorText || '--'}</div>;
          //     } else {
          //       return <div style={{ color: '#c4c4c3', paddingLeft: '8px' }}>自动带出</div>;
          //     }
          //   },
          // },
          {
            label: '预算金额',
            field: 'expectSum',
            placeholder: '自动计算',
            component: 'Input',
            disabled: true,
            contentAfter: '元',
          },
          {
            label: '标的来源',
            field: 'supplyWay',
            placeholder: '自动带出',
            component: 'Select',
            colSpan: 1,
            options: supplyWayList,
            disabled: true,
            fieldNames: {
              label: 'name',
              value: 'value',
            },
            suffixIcon: <></>,
          },
          {
            label: '采购组织类型',
            field: 'procureOrg',
            component: 'Render',
            slotRender: (text: any = 0) => {
              if (isShowSubmit) {
                return (
                  <div style={{ marginLeft: '8px' }}>
                    <TagSelect
                      colSpan={24}
                      formLabel={''}
                      formName={'procureOrg'}
                      defalultKeys={text || LaboratorySelfOrg() || undefined}
                      onChange={(val) => {
                        setPurchaseType(val);
                        methods?.setFieldValue('procureReal', undefined);
                        let newPackData = _?.cloneDeep(packData);
                        if (newPackData?.length) {
                          newPackData[page - 1].procureOrg = val;
                          newPackData[page - 1].procureReal = undefined;
                          setPackData(newPackData);
                        }
                      }}
                      radioList={[
                        {
                          value: LaboratorySelfOrg(),
                          name: '实验室自行组织',
                        },
                        {
                          value: GoveCentralPurchse(),
                          name: '政府集中采购',
                        },
                      ]}
                      radioDisabled={!isShowSubmit}
                    />
                  </div>
                );
              } else {
                return <span style={{ marginLeft: '8px' }}>{!text ? '实验室自行组织' : text == GoveCentralPurchse() ? '政府集中采购' : '实验室自行组织'}</span>;
              }
            },
            disabled: finallyType == 'view',
          },
          {
            label: '拟定采购方式',
            placeholder: '请选择',
            message: '请选择拟定采购方式',
            field: 'procureReal',
            component: 'TreeSelect',
            className: 'Descriptions-Apply-TreeSelect',
            treeData: orgTreeData(procureRealListMemo),
            treeIcon: false,
            disabled: !isShowSubmit,
            required: true,
            onSelect: (val) => {
              let newPackData = _?.cloneDeep(packData);
              newPackData[page - 1].procureReal = val;
              setPackData(newPackData);
            },
          },
          // {
          //   label: '资金来源编号',
          //   field: 'projectCode',
          //   component: 'Input',
          //   placeholder: '自动带出',
          //   disabled: true,
          //   contentAfter:
          //     finallyType == 'view' ? null : (
          //       <a>
          //         <SearchOutlined
          //           onClick={() => {
          //             onChangeSelectProjectState(true);
          //           }}
          //         />
          //       </a>
          //     ),
          // },
          {
            label: '采购方式变更申请单',
            field: 'changeApply',
            component: 'Render',
            colSpan: 2,
            slotRender: () => {
              return (
                <div style={{ paddingLeft: '8px' }}>
                  {applyInfo?.packs?.[page - 1]?.changeID ? (
                    <Tooltip title={'查看采购方式变更申请单'}>
                      <a>
                        <EyeOutlined
                          onClick={() => {
                            if (curRes?.['/purchaseSourceChangeController/getSourceChangeById/{id}/{currentUserID}']) {
                              history.push({
                                pathname: `/purchaseSourceChangeController/getSourceChangeById/{id}/{currentUserID}/:${getKeyRouter()}${getKeyRouter()}`,
                                state: {
                                  info: { changeID: applyInfo?.packs?.[page - 1]?.changeID },
                                  type: 'view',
                                },
                              });
                            } else {
                              message?.error('抱歉，暂无查看权限！');
                            }
                          }}
                        />
                      </a>
                    </Tooltip>
                  ) : (
                    // <EyeInvisibleOutlined />
                    <Tooltip title="暂无采购方式变更申请单">
                      <a>
                        <EyeInvisibleOutlined />
                      </a>
                    </Tooltip>
                  )}
                </div>
              );
            },
          },
          // {
          //   label: '资金来源父类',
          //   field: 'projectNameF',
          //   component: 'Input',
          //   required: true,
          //   disabled: true,
          //   placeholder: '请选择',
          // },
          // {
          //   label: '资金来源子类',
          //   field: 'projectNameZ',
          //   component: 'Input',
          //   required: true,
          //   disabled: true,
          //   placeholder: '请选择',
          // },
          {
            label: '意向公开名称',
            field: 'intentName',
            component: 'Input',
            placeholder: '自动带出',
            disabled: true,
            required: true,
            message: '请选择意向公开',
            contentAfter:
              finallyType == 'view' ? null : (
                <a>
                  <SearchOutlined onClick={() => setIsShowIntentModal({ isShow: true })} />
                </a>
              ),
          },
          {
            label: '意向公开时间',
            field: 'intentTime',
            component: 'Input',
            placeholder: '自动带出',
            disabled: true,
            required: true,
            message: '请选择意向公开',
          },
          {
            label: '技术规范',
            field: 'skillNormURL',
            placeholder: '请上传技术规范',
            component: 'Render',
            colSpan: 1,
            required: true,
            slotRender: (text, record) => {
              if (!isShowSubmit) {
                return (
                  <span style={{ marginLeft: 8 }}>
                    {renderFileFunc({
                      record: packData?.[page - 1] || {},
                      fileName: 'skillNormURL',
                      downloadAddress: '/purchaseApplyController/downloadFile',
                      returnStr: '/',
                    })}
                  </span>
                );
              }
              return (
                <div>
                  <UploadFormCommon
                    form={formRef}
                    fileFormName={'skillNormURL'}
                    spanCol={24}
                    inRowProportion={24}
                    name={'attachFile'}
                    required={true}
                    // accept={'.doc|.docx|.pdf'}
                    url={'/purchaseApplyController/uploadFile'}
                    downloadUrl={'/purchaseApplyController/downloadFile'}
                    fileFormDelName={'delFile'}
                    uploadSuccessCallback={(attachPaths) => {
                      let newPackData = _?.cloneDeep(packData);
                      if (newPackData?.length) {
                        newPackData[page - 1].skillNormURL = attachPaths;
                        setPackData(newPackData);
                      }
                    }}
                    defaultFiles={text}
                    maxFile={1}
                    hintTitle={'只能上传 1 个！'}
                    fieldBusiPath={'purchase/apply'}
                    delFunc={(delFilePath) => {}}
                  >
                    上传
                  </UploadFormCommon>
                </div>
              );
            },
          },
          {
            label: '调研报告',
            field: 'researchReportURL',
            placeholder: '请上传调研报告',
            component: 'Render',
            colSpan: 1,
            required: true,
            slotRender: (text, record) => {
              if (!isShowSubmit) {
                return (
                  <span style={{ marginLeft: 8 }}>
                    {renderFileFunc({
                      record: packData?.[page - 1] || {},
                      fileName: 'researchReportURL',
                      downloadAddress: '/purchaseApplyController/downloadFile',
                      returnStr: '/',
                    })}
                  </span>
                );
              }
              return (
                <div>
                  <UploadFormCommon
                    form={formRef}
                    fileFormName={'researchReportURL'}
                    spanCol={24}
                    inRowProportion={24}
                    name={'attachFile'}
                    required={true}
                    // accept={'.doc|.docx|.pdf'}
                    url={'/purchaseApplyController/uploadFile'}
                    downloadUrl={'/purchaseApplyController/downloadFile'}
                    fileFormDelName={'delFile'}
                    uploadSuccessCallback={(attachPaths) => {
                      let newPackData = _?.cloneDeep(packData);
                      if (newPackData?.length) {
                        newPackData[page - 1].researchReportURL = attachPaths;
                        setPackData(newPackData);
                      }
                    }}
                    defaultFiles={text}
                    maxFile={1}
                    hintTitle={'只能上传 1 个！'}
                    fieldBusiPath={'purchase/apply'}
                    delFunc={(url) => {}}
                  >
                    上传
                  </UploadFormCommon>
                </div>
              );
            },
          },
          {
            label: '是否进口',
            field: 'importFlag',
            component: 'Render',
            colSpan: !packData?.[page - 1]?.importFlag ? 2 : 1, // 修改点
            slotRender: (text: any = 0) => {
              if (!isShowSubmit) {
                return <span style={{ marginLeft: '8px' }}>{!text ? '否' : text == 1 ? '是' : '否'}</span>;
              } else {
                return (
                  <div style={{ marginLeft: '8px' }}>
                    <TagSelect
                      colSpan={24}
                      formLabel={''}
                      formName={'importFlag'}
                      defalultKeys={text || undefined}
                      onChange={(val) => {
                        let newPackData = _?.cloneDeep(packData);
                        if (newPackData?.length) {
                          newPackData[page - 1].importFlag = val;
                          setPackData(newPackData);
                        }
                      }}
                      radioList={[
                        {
                          value: 0,
                          name: '否',
                        },
                        {
                          value: 1,
                          name: '是',
                        },
                      ]}
                      radioDisabled={finallyType == 'view' || applyInfo?.state != QC_SQSTATE() || JSON.stringify(applyInfo) == '{}'}
                    />
                  </div>
                );
              }
            },
          },
          {
            label: '进口专业人员论证意见',
            field: 'needImportURL',
            placeholder: '请上传进口专业人员论证意见',
            component: 'Render',
            colSpan: 1,
            // ishidden: packData?.[page - 1]?.supplyWay && packData?.[page - 1]?.supplyWay == 1 && packData?.[page - 1]?.importFlag == 1 ? false : true,
            ishidden: packData?.[page - 1]?.importFlag == 1 ? false : true,
            required: true,
            slotRender: (text, record) => {
              if (!isShowSubmit) {
                return (
                  <span style={{ marginLeft: 8 }}>
                    {renderFileFunc({
                      record: packData?.[page - 1] || {},
                      fileName: 'needImportURL',
                      downloadAddress: '/purchaseApplyController/downloadFile',
                      returnStr: '/',
                    })}
                  </span>
                );
              }
              return (
                <div>
                  <UploadFormCommon
                    form={formRef}
                    fileFormName={'needImportURL'}
                    spanCol={24}
                    inRowProportion={24}
                    name={'attachFile'}
                    required={true}
                    // accept={'.doc|.docx|.pdf'}
                    url={'/purchaseApplyController/uploadFile'}
                    downloadUrl={'/purchaseApplyController/downloadFile'}
                    fileFormDelName={'delFile'}
                    uploadSuccessCallback={(attachPaths) => {
                      let newPackData = _?.cloneDeep(packData);
                      if (newPackData?.length) {
                        newPackData[page - 1].needImportURL = attachPaths;
                        setPackData(newPackData);
                      }
                    }}
                    defaultFiles={text}
                    maxFile={1}
                    hintTitle={'只能上传 1 个！'}
                    fieldBusiPath={'purchase/apply'}
                    delFunc={(delFilePath) => {}}
                  >
                    上传
                  </UploadFormCommon>
                </div>
              );
            },
          },
          {
            label: '是否单一来源',
            field: 'singleFlag',
            component: 'Render',
            colSpan: !packData?.[page - 1]?.singleFlag ? 2 : 1, // 修改点
            slotRender: (text) => {
              if (!isShowSubmit) {
                return <span style={{ marginLeft: '8px' }}>{!text ? '否' : Number(text) == 1 ? '是' : '否'}</span>;
              } else {
                return (
                  <div style={{ marginLeft: '8px' }}>
                    <TagSelect
                      colSpan={24}
                      formLabel={''}
                      formName={'singleFlag'}
                      defalultKeys={text || undefined}
                      onChange={(val) => {
                        let newPackData = _?.cloneDeep(packData);
                        if (newPackData?.length) {
                          newPackData[page - 1].singleFlag = val;
                          setPackData(newPackData);
                        }
                      }}
                      radioList={[
                        {
                          value: 0,
                          name: '否',
                        },
                        {
                          value: 1,
                          name: '是',
                        },
                      ]}
                      radioDisabled={finallyType == 'view' || applyInfo?.state != QC_SQSTATE() || JSON.stringify(applyInfo) == '{}'}
                    />
                  </div>
                );
              }
            },
          },
          {
            label: '单一来源论证意见',
            field: 'needSingleURL',
            placeholder: '请上传单一来源论证意见',
            component: 'Render',
            colSpan: 1,
            ishidden: packData?.[page - 1]?.singleFlag == 1 ? false : true,
            required: true,
            slotRender: (text, record) => {
              if (!isShowSubmit) {
                return (
                  <span style={{ marginLeft: 8 }}>
                    {renderFileFunc({
                      record: packData?.[page - 1] || {},
                      fileName: 'needSingleURL',
                      downloadAddress: '/purchaseApplyController/downloadFile',
                      returnStr: '/',
                    })}
                  </span>
                );
              }
              return (
                <div>
                  <UploadFormCommon
                    form={formRef}
                    fileFormName={'needSingleURL'}
                    spanCol={24}
                    inRowProportion={24}
                    name={'attachFile'}
                    required={true}
                    // accept={'.doc|.docx|.pdf'}
                    url={'/purchaseApplyController/uploadFile'}
                    downloadUrl={'/purchaseApplyController/downloadFile'}
                    fileFormDelName={'delFile'}
                    uploadSuccessCallback={(attachPaths) => {
                      let newPackData = _?.cloneDeep(packData);
                      if (newPackData?.length) {
                        newPackData[page - 1].needSingleURL = attachPaths;
                        setPackData(newPackData);
                      }
                    }}
                    defaultFiles={text}
                    maxFile={1}
                    hintTitle={'且只能上传 1 个！'}
                    fieldBusiPath={'purchase/apply'}
                    delFunc={(delFilePath) => {}}
                  >
                    上传
                  </UploadFormCommon>
                </div>
              );
            },
          },
          {
            label: '相关附件',
            field: 'relatedUrl',
            placeholder: '请上传相关附件',
            component: 'Render',
            colSpan: 2,
            required: true,
            slotRender: (text, record) => {
              if (!isShowSubmit) {
                return (
                  <span style={{ marginLeft: 8 }}>
                    {renderFileFunc({
                      record: packData?.[page - 1] || {},
                      fileName: 'relatedUrl',
                      downloadAddress: '/purchaseApplyController/downloadFile',
                      returnStr: '/',
                    })}
                  </span>
                );
              }
              return (
                <div style={{ width: '50%', overflow: 'hidden' }}>
                  <UploadFormCommon
                    form={formRef}
                    fileFormName={'relatedUrl'}
                    spanCol={24}
                    inRowProportion={12}
                    name={'attachFile'}
                    required={true}
                    url={'/purchaseApplyController/uploadFile'}
                    downloadUrl={'/purchaseApplyController/downloadFile'}
                    fileFormDelName={'delFile'}
                    uploadSuccessCallback={(attachPaths) => {
                      let newPackData = _?.cloneDeep(packData);
                      if (newPackData?.length) {
                        newPackData[page - 1].relatedUrl = attachPaths;
                        setPackData(newPackData);
                      }
                    }}
                    defaultFiles={text}
                    maxFile={5}
                    hintTitle={'且只能上传 5 个！'}
                    fieldBusiPath={'purchase/apply'}
                    delFunc={(delFilePath) => {}}
                  >
                    上传
                  </UploadFormCommon>
                </div>
              );
            },
          },
          {
            label: '需求论证意见',
            field: 'needProofURL',
            placeholder: '请上传需求论证意见',
            component: 'Render',
            colSpan:
              packData?.[page - 1]?.supplyWay == 1 && packData?.[page - 1]?.expectSum && Number(packData?.[page - 1]?.expectSum) >= 500000
                ? Number(packData?.[page - 1]?.expectSum) >= 1000000
                  ? 1
                  : 2
                : 0,
            required: true,
            ishidden:
              packData?.[page - 1]?.supplyWay == 1 && packData?.[page - 1]?.expectSum && Number(packData?.[page - 1]?.expectSum) >= 500000 ? false : true,
            slotRender: (text, record) => {
              if (!isShowSubmit) {
                return (
                  <span style={{ marginLeft: 8 }}>
                    {renderFileFunc({
                      record: packData?.[page - 1] || {},
                      fileName: 'needProofURL',
                      downloadAddress: '/purchaseApplyController/downloadFile',
                      returnStr: '/',
                    })}
                  </span>
                );
              }
              return (
                <div>
                  <UploadFormCommon
                    form={formRef}
                    fileFormName={'needProofURL'}
                    spanCol={24}
                    inRowProportion={24}
                    name={'attachFile'}
                    required={true}
                    // accept={'.doc|.docx|.pdf'}
                    url={'/purchaseApplyController/uploadFile'}
                    downloadUrl={'/purchaseApplyController/downloadFile'}
                    fileFormDelName={'delFile'}
                    uploadSuccessCallback={(attachPaths) => {
                      let newPackData = _?.cloneDeep(packData);
                      if (newPackData?.length) {
                        newPackData[page - 1].needProofURL = attachPaths;
                        setPackData(newPackData);
                      }
                    }}
                    defaultFiles={text}
                    maxFile={1}
                    hintTitle={'且只能上传 1 个！'}
                    fieldBusiPath={'purchase/apply'}
                    delFunc={(delFilePath) => {}}
                  >
                    上传
                  </UploadFormCommon>
                </div>
              );
            },
          },
          {
            label: '是否通过主任办公室会议',
            field: 'directorMeetingFlag',
            placeholder: '请上传是否通过主任办公室会议',
            component: 'Render',
            colSpan: packData?.[page - 1]?.supplyWay == 1 && packData?.[page - 1]?.expectSum && Number(packData?.[page - 1]?.expectSum) >= 1000000 ? 1 : 0,
            ishidden:
              packData?.[page - 1]?.supplyWay == 1 && packData?.[page - 1]?.expectSum && Number(packData?.[page - 1]?.expectSum) >= 1000000 ? false : true,
            required: true,
            slotRender: (text, record) => {
              return (
                <div style={{ marginLeft: '8px' }}>
                  <Checkbox
                    onChange={(val) => {
                      let newPackData = _?.cloneDeep(packData);
                      if (newPackData?.length) {
                        newPackData[page - 1].directorMeetingFlag = Number(val?.target?.checked);
                        setPackData(newPackData);
                      }
                    }}
                    checked={Boolean(packData[page - 1].directorMeetingFlag)}
                  >
                    本人确认已通过主任办公室审议!
                  </Checkbox>
                </div>
              );
            },
          },

          // 隐藏不展示字段 便于保存表单
          // {
          //   label: '意向公开ID',
          //   field: 'intentID',
          //   placeholder: '意向公开ID',
          //   component: 'Input',
          //   ishidden: true
          // }
        ],
      },
    ],
  });

  /** 标的信息配置 */
  const { rowSelection, selectedRows, selectedRowKeys, targetDataSource, setTartetDataSource } = useStepTarget();

  /** 采购申请标包hooks */
  const { change, remove, isShowMaterial } = useStepPack({
    // hooks
    setPackData,
    setPage,
    setTartetDataSource,
    setLoading,
    methods,
    dispatch,
    state: {
      applyInfo,
      packData,
      page,
      ProjectInfo,
      successMaterials,
      setSuccessMaterials,
      reloadInfoService,
    },
  });

  /** 解构change方法 */
  const { addPack, initAddPack, changePage, changeTargetInfo, changePiecemealInfo } = change;

  /** 解构remove */
  const { removeMaterialInfo, setRemoveMaterialInfo, onRemove } = remove;

  /** 暴露给父组件的实例值 */
  useImperativeHandle(ref, () => ({
    validateFields: () => {
      return new Promise(async (resolve) => {
        const result = await methods.validateFields();
        const tempData = lodash.cloneDeep(packData);
        tempData[page - 1] = {
          ...tempData[page - 1],
          ...result,
        };

        setPackData(tempData);
        if (!tempData.length) {
          resolve(false);
        } else {
          resolve(tempData);
        }
      });
    },
  }));

  /** 监听详情，控制page 最好别动此处代码 */
  useEffect(() => {
    if (Object.keys(applyInfo).length) {
      if (applyInfo?.packs?.length) {
        /** 处理数据 */
        const newdata = handleReturnObjectData(applyInfo?.packs?.length ? [...applyInfo?.packs] : []);
        // 存储选择的标包信息
        setPackData(newdata);
        if (page == 1) {
          changePage('reset', newdata);
        } else {
          if (page == 0) {
            changePage('final', newdata, 1);
          } else {
            if (page <= newdata?.length) {
              changePage('final', newdata, page);
            } else {
              changePage('final', newdata, newdata?.length);
            }
          }
        }
      } else {
        if (packData?.length) {
          if (page != 1) {
            changePage('final', packData, page);
          } else {
            changePage('reset', packData);
          }
        } else if (applyInfo?.expectSum === 0) {
          addPack();
        }
      }
    }
  }, [applyInfo]);

  useEffect(() => {
    const flag = packData?.find((item) => item?.id);
    if (!flag) {
      const newpackData = _?.cloneDeep(packData);
      newpackData?.forEach((item) => {
        item.supplyWay = applyInfo?.supplyWay;
      });
      setPackData(newpackData);
      methods?.setFieldValue('supplyWay', applyInfo?.supplyWay);
      initAddPack();
    }
  }, [applyInfo?.supplyWay]);

  /** 监听page */
  useEffect(() => {
    const tempData = lodash.cloneDeep(packData);
    /** 处理详情接口回来的包列表 */
    const { packs } = applyInfo;
    if (packs && page) {
      /** 将当前包数据推入 */
      const data = [...packs];
      const successTargets: any = [];
      if (page >= 1 && data?.length) {
        data?.[page - 1]?.mpurchaseNeedMaterials?.forEach((ite: Record<string, any>) => {
          successTargets?.push(ite);
        });
      }
      const newMaterilList = processObjects(successTargets);
      setSuccessMaterials(newMaterilList);
      packs?.forEach((item, index) => {
        tempData[index].mpurchaseNeedMaterials = item?.mpurchaseNeedMaterials;
      });
      // setPackData(tempData); // 更新标包数据
      setPurchaseType(tempData[page - 1]?.procureOrg || LaboratorySelfOrg()); // 更新采购组织形式
    }
    dispatch({ type: IContractsActionEnum.UpdatePage, payload: page });
  }, [page]);

  const selectMList = useMemo(() => {
    if (!packData?.length) [];
    else {
      let data: any = [...packData];
      let allMlist: Record<string, any>[] = [];
      data?.forEach((item) => {
        item?.mpurchaseNeedMaterials?.forEach((ite) => {
          ite?.customNeedMatrials?.forEach((tem) => {
            allMlist?.push(tem);
          });
        });
      });
      const newArr = combineObjects(allMlist);
      return newArr;
    }
    return [];
  }, [packData]);

  return (
    <>
      {applyInfo?.packs == undefined && finallyType == 'view' ? (
        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
      ) : (
        <div className={`${prefixCls}-steps-pack`}>
          {packData?.[page - 1]?.id && applyInfo?.state != QC_SQSTATE() && applyInfo?.state != SHZ_SQSTATE() && applyInfo?.state != ZF_SQSTATE() ? (
            <>
              {packData[page - 1]?.finishState == 0 ? (
                <MyIcon
                  type="icon-weiwanchengc"
                  style={{
                    fontSize: '60px',
                    position: 'absolute',
                    right: '20px',
                    zIndex: '1',
                    transform: 'rotate(32deg)',
                  }}
                />
              ) : (
                <MyIcon
                  type="icon-yiwanchengc"
                  style={{
                    fontSize: '60px',
                    position: 'absolute',
                    right: '20px',
                    zIndex: '1',
                    transform: 'rotate(32deg)',
                  }}
                />
              )}
            </>
          ) : (
            <></>
          )}
          <Spin spinning={loading || mapLoading}>
            <div className={`${prefixCls}-steps-pack-operate`}>
              {finallyType != 'view' && applyInfo?.id && (
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  style={{ marginRight: '8px' }}
                  onClick={async () => {
                    // await onClickSave()
                    // setTimeout(() => {
                    // }, 0)
                    addPack();
                  }}
                >
                  添加标包
                </Button>
              )}

              {packData.length > 0 && finallyType != 'view' && applyInfo?.id && (
                <Button
                  type="primary"
                  danger
                  icon={<DeleteOutlined />}
                  onClick={() => {
                    setRemoveMaterialInfo({
                      id: '',
                      index: 0,
                      name: '标包',
                      content: methods.getFieldValue('packName'),
                      // content:''
                      type: 'pack',
                      isShow: true,
                      isBatch: false,
                    });
                  }}
                >
                  删除标包
                </Button>
              )}
            </div>
            <DescriptionsType config={config} />
            {finallyType != 'view' && applyInfo?.id && (
              <div className={`${prefixCls}-steps-pack-operate batch-remove`}>
                <Button
                  type="primary"
                  danger
                  icon={<DeleteOutlined />}
                  onClick={() => {
                    setRemoveMaterialInfo({
                      id: selectedRowKeys.join(','),
                      index: 0,
                      name: methods.getFieldValue('packName'),
                      content: selectedRows.map((item) => item.fullName).join('，'),
                      type: 'target',
                      isShow: true,
                      isBatch: true,
                    });
                  }}
                >
                  批量删除
                </Button>
              </div>
            )}
            <div className={'apply-update-title-divClassName'}>
              <div style={{ fontSize: '20px' }}>
                二、标包物料
                <span
                  style={{
                    fontSize: 18,
                    fontWeight: 400,
                    color: 'red',
                    marginLeft: '5px',
                  }}
                >
                  {`(提示：每个标包内的物料或服务应来源于同一潜在供应商)`}
                </span>
              </div>
            </div>
            <div className={Cls(`list-table`, 'applyUpdatePackTable')} style={{ flex: 'auto', height: '100%', overflow: 'hidden' }}>
              <Table
                bordered
                size="small"
                rowKey={'id'}
                pagination={false}
                rowClassName={setTableRowClassName}
                scroll={{ x: 1000 }}
                dataSource={targetDataSource}
                rowSelection={finallyType == 'view' ? undefined : rowSelection}
                columns={getPackTableColumns({
                  applyInfo,
                  finallyType,
                  onSelectProject: (record) => {
                    if (applyInfo?.id && applyInfo?.supplyWay == 1) {
                      setIsShowProjectModal({ isShow: true, resObj: record });
                    }
                  },
                  selectModal: (obj) => {
                    if (applyInfo?.id && applyInfo?.supplyWay == 1) {
                      // 零星采购-选择物料列表
                      setAfewMetailModal({ isShow: true, resObj: applyInfo });
                      return;
                    }
                    // 月度计划-选择计划物料列表
                    changeTargetInfo(obj);
                  },
                  onRemove: (id: string, index: number, name: string) => {
                    setRemoveMaterialInfo({
                      id: id,
                      index: index,
                      name: methods.getFieldValue('packName'),
                      content: name,
                      type: 'target',
                      isShow: true,
                      isBatch: false,
                    });
                  },
                })}
                onRow={(record) => {
                  return {
                    onClick: (event) => {
                      event.stopPropagation();
                    },
                  };
                }}
              />
            </div>

            {/* 底部标包条数 */}
            <CustomPaging current={page} total={packData.length} onChange={(opertae) => changePage(opertae)} />
          </Spin>

          {/* 删除物料确认弹窗 */}
          {removeMaterialInfo.isShow && (
            <UpdateRemoveModal
              info={removeMaterialInfo}
              onSubmit={onRemove}
              onClose={() => setRemoveMaterialInfo({ id: '', index: 0, name: '', content: '', type: '', isShow: false, isBatch: false })}
            />
          )}

          {/* 月度计划-选择弹窗 */}
          {isShowMaterial && (
            <UpdateMaterialModal
              successMaterials={successMaterials}
              selectMaterialList={selectMList}
              onSave={(packInfo) => changeTargetInfo({ packInfo, isShow: true })}
              onClose={() => changeTargetInfo({ packInfo: {}, isShow: false })}
            />
          )}

          {/* 零星采购-选择弹窗 */}
          {afewMetailModal?.isShow && (
            <AfewMetailModalCpt
              onClose={() => setAfewMetailModal({})}
              onSave={(resObj) => changePiecemealInfo({ packInfo: { mpurchaseNeedMaterials: resObj }, isShow: true, flag: false })}
              materialList={packData?.[page - 1]?.mpurchaseNeedMaterials}
            />
          )}

          {/* 资金来源--弹窗 */}
          {/* {isShowSelectProject && (
            <UpdateProjectModal
              onSave={(param: Record<string, any>) => onChangeSelectProjectState(true, param)}
              onClose={() => onChangeSelectProjectState(false)}
            />
          )} */}

          {/* 项目资金来源弹窗 */}
          {/* {
            isShowSelectProject &&
            <SelectProjectModal
              curRes={curRes}
              onClose={() => onChangeSelectProjectState(false)}
              onSave={() => { }}
            />
          } */}

          {/* 项目来源弹窗 */}
          {isShowProjectModal?.isShow && (
            <SelectProjectModal
              onClose={() => setIsShowProjectModal({})}
              onSave={(resObj) => {
                let obj = {
                  projectCode: resObj?.xmdm,
                  projectName: resObj?.xmmc,
                  projectSum: resObj?.ysje,
                };
                const newpackData = _?.cloneDeep(packData);
                const key = isShowProjectModal?.resObj?.id;
                const packMateril = _?.cloneDeep(newpackData?.[page - 1]?.mpurchaseNeedMaterials);
                packMateril?.forEach((item) => {
                  if (item.id == key) {
                    item.projectCode = resObj?.xmdm;
                    item.projectName = resObj?.xmmc;
                    item.projectSum = resObj?.ysje;
                  }
                });
                newpackData[page - 1].mpurchaseNeedMaterials = packMateril;
                changePiecemealInfo({ packInfo: { mpurchaseNeedMaterials: packMateril }, isShow: true, flag: false });
                // setPackData(newpackData);
              }}
            />
          )}

          {/* 意向公开弹窗 */}
          {isShowIntentModal?.isShow && (
            <IntentModal
              curRes={curRes}
              onClose={() => setIsShowIntentModal({})}
              onSave={(resObj) => {
                const newpackData = _?.cloneDeep(packData);
                newpackData?.forEach((item, index) => {
                  if (index == page - 1) {
                    item.intentID = resObj?.id;
                    item.intentName = resObj?.intentName;
                    item.intentTime = resObj?.intentTime;
                  }
                });
                setPackData(newpackData);
                methods.setFieldsValue({
                  intentTime: resObj?.intentTime || '',
                  intentName: resObj?.intentName || '',
                  intentID: resObj?.id || '',
                });
              }}
            />
          )}
        </div>
      )}
    </>
  );
});

export default UpdateStepsPack;
